<?php

namespace app\jun\controller;

use app\erp\model\Attrdb;
use app\erp\model\Cartdb;
use app\erp\model\Categorydb;
use app\erp\model\Expressdb;
use app\erp\model\JunCitydb;
use app\erp\model\JunResultdb;
use app\erp\model\Kdresultdb;
use app\erp\model\Memberdb;
use app\erp\model\OrderLogdb;
use app\erp\model\Postwuliudb;
use app\erp\model\Returneddb;
use app\erp\model\Runsdb;
use app\erp\model\UInvoicedb;
use app\erp\model\UOrderdb;
use app\erp\model\Uploaddb;
use app\erp\validate\Attrrule;

//use http\Header;
use think\Controller;
use app\erp\model\Goodsdb;
use app\erp\model\Sitedb;
use app\erp\model\Orderdb;

class Api extends Controller
{
    protected $ys_config = [
        'geteway' => 'https://tailongji.dixintong.com/erp/api/',
        'partnerId' => 25,
        'siteId' => 117,
        'appId' => 'utec',
        'appKey' => 'yserp',
        'appSecret' => 'duXtRelcYy2sJeqrLpmNvbQO0O0OO0O0O'
    ];
    protected $api_url = 'https://zc.plap.mil.cn/api/';
    protected $appKey = 'zXAOSQxT';
    protected $appSecret = '7x0DzpqUlS';
    protected $request = array();

    public function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        header('Content-Type:application/json; charset=utf-8');
        $request = request();
        $this->request = $request->param();
        if (!defined('SITE_ID')) {
            define('SITE_ID', 117);
        }
        if (!defined('PARTNER_ID')) {
            define('PARTNER_ID', 25);
        }
        if (!defined('MEMBER_ID')) {
            define('MEMBER_ID', 193);
        }
    }

    // 返回值
    protected function ajaxReturn($return, $json_option = 0)
    {
        header('Content-Type:application/json; charset=utf-8');
        exit (json_encode($return, $json_option));
    }

    public function sendInfo($string_uri, $post)
    {
        if ($string_uri != 'ecservice/getAccessToken') {
            $post ['accessToken'] = $this->getAccessToken();
            $post ['appKey'] = $this->appKey;
        }
        $json_data = json_encode($post);
        //print_r($json_data);
        /*
         * print_r('提交参数:');
         * print_r($json_data);
         * print_r('提交网址：');
         * print_r($this->api_url . $string_uri);
         * print_r(chr(13));
         */
        /*print_r('提交参数:');
        print_r($json_data);
        print_r('提交网址：');
        print_r($this->api_url . $string_uri);
        print_r(chr(13));*/
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api_url . $string_uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-type: application/json;charset='utf-8'"
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        $return_json = json_decode($result, true);
        if (!isset ($return_json ['isSuccess']) || $return_json ['isSuccess'] != 1) {
            /*
             * print_r ( '提交参数:' );
             * print_r ( $json_data );
             * print_r ( '提交网址：' );
             * print_r ( $this->api_url . $string_uri );
             * print_r ( chr ( 13 ) );
             * print_r ( '返回信息：' );
             * print_r ( $return_json );
             */
            return $return_json;
        } else {
            return $return_json;
        }
    }

    // 获取token
    public function getAccessToken()
    {
        $sitedb = new Sitedb ();
        $get_site = $sitedb->ajaxFind(SITE_ID);
        /*
        $post_json ['appKey'] = $this->appKey;
        $post_json ['appSecret'] = $this->appSecret;
        $result = $this->sendInfo ( 'ecservice/getAccessToken', $post_json );
        $token = $result ['accessToken'];
        $sitedb->save ( [
                'access_token' => $token,
                'expires_stop_time' => time ()
        ], [
                'site_id' => SITE_ID
        ] );
        */

        if ($get_site ['access_token']) {
            if (time() >= $get_site ['expires_stop_time'] + 86400) {
                $post_json ['appKey'] = $this->appKey;
                $post_json ['appSecret'] = $this->appSecret;
                $result = $this->sendInfo('ecservice/getAccessToken', $post_json);
                $token = $result ['accessToken'];
                $sitedb->save([
                    'access_token' => $token,
                    'expires_stop_time' => time()
                ], [
                    'site_id' => SITE_ID
                ]);
            } else {
                $token = $get_site ['access_token'];
            }
        } else {
            $post_json ['appKey'] = $this->appKey;
            $post_json ['appSecret'] = $this->appSecret;
            $result = $this->sendInfo('ecservice/getAccessToken', $post_json);
            $token = $result ['accessToken'];
            $sitedb->save([
                'access_token' => $token,
                'expires_stop_time' => time()
            ], [
                'site_id' => SITE_ID
            ]);
        }

        return $token;
        // print_r($result['accessToken']);
    }

    // 6.2.1 获取品类
    public function getProductCategory()
    {
        $result = $this->sendInfo('ecservice/getProductCategory', array());
        //print_r($result);
        print_r($result ['result']);
    }

    // 6.2.2 获取标准参数
    public function ajaxCidParams($categoryId)
    {
        $categorydb = new Categorydb();
        $get_category = $categorydb->where('api_option', $categoryId)->where('site_id', 117)->find();
        if ($get_category) {
            $category_info = $get_category->toArray();
            $post_json['categoryId'] = $categoryId;
            $result = $this->sendInfo('ecservice/getCidParams', $post_json);
            foreach ($result['paramList'] as $key => $val) {
                $save_temp = array();
                $save_temp['category_sign'] = $category_info['category_sign'];
                $save_temp['attr_name'] = $val['param_name'];
                $save_temp['group_names'] = $val['grouping_name'];
                $save_temp['is_must'] = $val['ismust'] == 1 ? 1 : 2;
                if ($val['input_type'] == 1) {
                    $save_temp['value_type'] = 2;
                    $save_temp['select_type'] = 1;
                } elseif ($val['input_type'] == 2) {
                    $save_temp ['value_type'] = 3;
                    $save_temp['select_type'] = 2;
                } else {
                    $save_temp['value_type'] = 1;
                }
                $save_temp['site_id'] = 117;
                $save_temp['admin_id'] = 193;
                $save_temp['sort'] = $val['ordernum'];
                $ts = array();
                if (count($val['paramsvalues']) > 0) {
                    foreach ($val['paramsvalues'] as $k => $v) {
                        array_push($ts, $v['value_text']);
                    }
                }
                $save_temp['value_item'] = implode(',', $ts);
                $save_temp['is_update'] = 'yes';
                $attrdb = new Attrdb();

                $attrdb->param = $save_temp;
                $result = $attrdb->ajaxSave();
                echo '<div>' . $save_temp['attr_name'] . '[保存结果：' . $attrdb->lastInsSign . '(' . $result . ')]</div>';
            }
        } else {
            halt($categoryId . '分类未找到');
        }
    }

    // 6.2.2 获取标准参数
    public function getCidParams()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/getCidParams', $post_json);
        print_r($result['paramList']);
        //halt($result ['paramList']);
    }

    // 6.2.3 修改为获取品牌
    public function getBrand()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/getBrands', $post_json);
        return json($result);
    }

    // 获取品牌接口
    public function getBrandApi(){
        $post_json['page_no'] = 1;
        $post_json['per'] = 100000;
        $result = $this->sendInfo('ecservice/getBrands', $post_json);
        return $result;
    }

    // 6.2.3 参数增量
    public function getNewCidList()
    {
        $post_json ['startDate'] = date('Y-m-d', strtotime('-1 day', time())) . ' 00:00:00';
        $post_json ['endDate'] = date('Y-m-d', strtotime('-1 day', time())) . ' 23:59:59';
        $result = $this->sendInfo('rest/ecservice/getNewCidList', $post_json);
        return $result;
    }

    // 6.2.4 重点商品明细接口
    public function getSkuDetail()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/getSkuDetail', $post_json);
        print_r($result);
    }

    // 今日重点商品采集
    public function callet($page = 1)
    {
        set_time_limit(0);
        $limit = 300;
        // $limit = $limit;
        $result = $this->returnNewSkuList();
        $end = count($result);
        $post_data ['callet_juncai'] = 1;
        $post_data ['admin_id'] = 193;
        $post_data ['site_id'] = 117;
        $post_data ['category_sign1'] = 'cb879747851c8d1042f680fb0d2da49f';
        $post_data ['category_sign2'] = '5b75df97d1b4034b75f235260196005e';
        $post_data ['category_sign3'] = '72605d67c737bb328e50295092d0d79b';
        $post_data ['brand_sign'] = '032fe3e7e08d6ac761ddeb51fa477e0b';
        for ($i = ($page - 1) * $limit; $i < ($end > $page * $limit ? $page * $limit : $end); $i++) {
            $get_detail = $this->calletSkuDetail($result [$i]);
            $price = $get_detail ['price'] ? $get_detail ['price'] : 0;
            $post_data ['goods_sku'] = $get_detail ['sku'];
            $post_data ['jun_id'] = $get_detail ['productcode'];
            $post_data ['jun_brandid'] = $get_detail ['brandid'];
            $post_data ['goods_name'] = $get_detail ['name'];
            $post_data ['goods_model'] = $get_detail ['model'];
            $post_data ['goods_content'] = $get_detail ['introduction'];
            $post_data ['junsale_state'] = $get_detail ['state'] == 1 ? 1 : 2;
            $post_data ['sale_state'] = $get_detail ['auditstatus'] == 1 ? 1 : 2;
            $post_data ['api_option'] = json_encode($get_detail);
            $post_data ['market_price'] [0] = $price;
            $post_data ['sale_price'] [0] = $price;
            $post_data ['api_price'] [0] = $price;
            $post_data ['cid'] = $get_detail ['cid'];
            $post_data ['sale_attr_price_name'] [0] = '商品价格';
            $post_data ['give_score'] [0] = 0;
            $post_data ['view_stock'] [0] = 0;
            $post_data ['is_zhongdian'] = 1;
            // 保存封面图
            if (isset($get_detail['images'])) {
                $uploaddb = new Uploaddb();
                $uploaddb->param['type'] = 'png';
                $uploaddb->param['size'] = rand(100, 99999);
                $uploaddb->param['save_path'] = $get_detail['images'];
                $uploaddb->param['file_name'] = time() . '.png';
                $get_upload = $uploaddb->ajaxSave();
                $post_data['goods_picture'] = $get_upload['upload_id'];
            }
            $goodsdb = new Goodsdb ();
            $goodsdb->param = $post_data;
            $goodsdb->ajaxSaveJuncai();
        }
        echo('共：' . count($result) . '条数据，本次采集到：' . $i . '条');
        if ($i < count($result)) {
            $url = url('api/callet', array(
                'page' => ++$page
            ));
            //   header("Location:".$url);
            // die();
            //  echo "<script>window.location.href='" . $url . "'</script>";
        } else {
            echo '采集完成';
        }
    }

    // 昨日重点商品采集
    public function daycallet($page = 1)
    {
        set_time_limit(0);
        $limit = 500;
        // $limit = $limit;
        $result = $this->dayreturnNewSkuList();

        $end = count($result);
        $post_data ['callet_juncai'] = 1;
        $post_data ['admin_id'] = 193;
        $post_data ['site_id'] = 117;
        $post_data ['category_sign1'] = 'cb879747851c8d1042f680fb0d2da49f';
        $post_data ['category_sign2'] = '5b75df97d1b4034b75f235260196005e';
        $post_data ['category_sign3'] = '72605d67c737bb328e50295092d0d79b';
        $post_data ['brand_sign'] = '032fe3e7e08d6ac761ddeb51fa477e0b';
        for ($i = ($page - 1) * $limit; $i < ($end > $page * $limit ? $page * $limit : $end); $i++) {
            $get_detail = $this->calletSkuDetail($result [$i]);
            $price = $get_detail ['price'] ?? 0;
            $post_data ['goods_sku'] = $get_detail ['sku'];
            $post_data ['jun_id'] = $get_detail ['productcode'];
            $post_data ['jun_brandid'] = $get_detail ['brandid'];
            $post_data ['goods_name'] = $get_detail ['name'];
            $post_data ['goods_model'] = $get_detail ['model'];
            $post_data ['goods_content'] = $get_detail ['introduction'];
            $post_data ['junsale_state'] = $get_detail ['state'] == 1 ? 1 : 2;
            $post_data ['sale_state'] = $get_detail ['auditstatus'] == 1 ? 1 : 2;
            $post_data ['api_option'] = json_encode($get_detail);
            $post_data ['market_price'] [0] = $price;
            $post_data ['sale_price'] [0] = $price;
            $post_data ['api_price'] [0] = $price;
            $post_data ['cid'] = $get_detail ['cid'];
            $post_data ['sale_attr_price_name'] [0] = '商品价格';
            $post_data ['give_score'] [0] = 0;
            $post_data ['view_stock'] [0] = 0;
            $post_data ['is_zhongdian'] = 1;
            // 保存封面图
            if (isset($get_detail['images'])) {
                $uploaddb = new Uploaddb();
                $uploaddb->param['type'] = 'png';
                $uploaddb->param['size'] = rand(100, 99999);
                $uploaddb->param['save_path'] = $get_detail['images'];
                $uploaddb->param['file_name'] = time() . '.png';
                $get_upload = $uploaddb->ajaxSave();
                $post_data['goods_picture'] = $get_upload['upload_id'];
            }
            $goodsdb = new Goodsdb ();
            $goodsdb->param = $post_data;
            $goodsdb->ajaxSaveJuncai();
        }
        echo('共：' . count($result) . '条数据，本次采集到：' . $i . '条');
        if ($i < count($result)) {
            $url = url('api/daycallet', array(
                'page' => ++$page
            ));
            echo "<script>window.location.href='" . $url . "'</script>";
        } else {
            echo '采集完成';
        }
    }

    // 6.2.4 重点商品明细接口
    public function calletSkuDetail($sku)
    {
        $post_json ['sku'] = $sku;
        $result = $this->sendInfo('ecservice/getSkuDetail', $post_json);
        return $result;
    }

    // 6.2.5 重点商品增量清单
    public function getNewSkuList()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/getNewSkuList', $post_json);
        return json(isset($result ['skuList']) ? $result ['skuList'] : array());
    }

    // 返回今日重点商品
    public function returnNewSkuList()
    {
        $post_json = $this->request;
        $post_json ['startDate'] = date("Y-m-d H:i:s", strtotime('-15 minute', time()));
        $post_json ['endDate'] = date("Y-m-d H:i:s");
        //    $post_json ['startDate'] = '2023-02-07 04:00:01';
        //    $post_json ['endDate'] = '2023-02-07 14:07:59';
        //  halt($post_json);
        $result = $this->sendInfo('ecservice/getNewSkuList', $post_json);
        return isset($result ['skuList']) ? $result ['skuList'] : array();
    }

    // 返回昨日重点商品
    public function dayreturnNewSkuList()
    {
        $post_json = $this->request;
        //  $post_json ['startDate'] = date("Y-m-d H:i:s", strtotime('-360 minute', time()));
        //  $post_json ['endDate'] = date("Y-m-d H:i:s");
        $post_json ['startDate'] = date('Y-m-d', strtotime('-1 day', time())) . ' 00:00:01';
        //$post_json ['endDate'] = date('Y-m-d', strtotime('-1 day', time())) . ' 23:59:59';
        $post_json ['endDate'] = date("Y-m-d H:i:s");
        //     $post_json ['startDate'] = '2023-03-30 00:00:01';
        //     $post_json ['endDate'] = '2023-03-30 23:59:59';
        $result = $this->sendInfo('ecservice/getNewSkuList', $post_json);
        // halt($result);
        return isset($result ['skuList']) ? $result ['skuList'] : array();
    }

    // 6.2.6 地址
    public function getAddressList()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/getAddressList', $post_json);
        // 同步数据到本地
        /*$junCitydb = new JunCitydb();
        $save_temp = [];
        foreach ($result['result'] as $key => $val) {
            $temp = [];
            $temp['cityname'] = $val['cityname'];
            $temp['citycode'] = $val['citycode'];
            array_push($save_temp,$temp);
        }
        $junCitydb->saveAll($save_temp);*/
        print_r($result);
    }

    // 6.2.6 地址
    public function getAddressInfo($id)
    {
        $post_json ['citycode'] = $id;
        $result = $this->sendInfo('ecservice/getAddressList', $post_json);
        return $result;
    }
    // 6.3.3 商品更新消息推送
    /*
     * 保存商品的时候需要调用该接口
     * "skuInfo":[{sku:"120855119",updateType:"1"},{sku:"120855111",updateType:"2"}]
     * 1新增，2商品信息更新，3图片更新，4商品上架，5商品下架，6价格更新
     （1）2、3只针对审核不通过后的商品进行更新重新提交审核，待审核、审核通过商品不能修改信息
     （2）4、5、6只针对自选商品，重点商品审核通过后通过6.2.5接口重新获取该商品，且报价、下架也通过6.3.8接口进行操作。
     （3）重点商品下单调电商接口时根据自采平台的商品id标识商品，自选商品则根据电商的sku标识商品
     */
    public function sendproductupdateinfo()
    {
        // 模拟信息
        $data = array();
        $temp ['sku'] = 'SKU1749075409431129';
        $temp ['updateType'] = 2;
        array_push($data, $temp);
        // 模拟信息
        $post_json ['skuInfo'] = $data;
        $result = $this->sendInfo('ecservice/sendproductupdateinfo', $post_json);
        print_r($result);
    }

    public function ajaxproductupdateinfo($data)
    {
        $post_json ['skuInfo'] = $data;
        $result = $this->sendInfo('ecservice/sendproductupdateinfo', $post_json);
        return $result;
    }

    // 6.3.6 商品状态校验
    public function checkproductstatus()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/checkProductStatus', $post_json);
        print_r($result);
    }

    public function returnProductStatus($goods_skus)
    {
        $post_json ['skuList'] = $goods_skus;
        $result = $this->sendInfo('ecservice/checkProductStatus', $post_json);
        return $result;
    }
    // 6.3.8 重点商品报价
    /*
     *
     */
    public function queryCountPrice()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/queryCountPrice', $post_json);
        print_r($result);
    }

    public function ajaxCountPrice($post_json)
    {
        // print_r($post_json);
        $result = $this->sendInfo('ecservice/queryCountPrice', $post_json);
        return $result;
    }

    // 6.3.9 商品更新审批结果
    public function getApprovalResult()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/getApprovalResult', $post_json);
        print_r($result);
    }

    // 6.3.9 商品更新审批结果
    public function ajaxApprovalResult()
    {
        $post_json['startDate'] = date('Y-m-d', strtotime('-14 day', time())) . ' 00:00:00';
        $post_json['endDate'] = date('Y-m-d 23:59:59', time());
        //  $post_json['startDate'] = '2022-05-14 00:00:00';
        $result = $this->sendInfo('ecservice/getApprovalResult', $post_json);
        if (isset($result['skulist'])) {
            foreach ($result['skulist'] as $key => $val) {
                $goodsdb = new Goodsdb();
                if ($val['sku']) {
                    $goods_sku = $val['sku'];
                    $temp = array();
                    $temp['jun_state'] = $val['state'];
                    $temp['operatedate'] = $val['operatedate'];
                    $temp['details'] = '';
                    if (isset($val['details'])) {
                        $temp['details'] = $val['details'];
                    }
                    if (isset($val['productcode'])) {
                        $temp['jun_id'] = $val['productcode'];
                    }
                    $goodsdb->where('goods_sku', $goods_sku)->update($temp);
                }
            }
        }
        print_r('success');
    }

    // 6.5.5 订单状态校验接口
    public function checkOrderStatus()
    {
        $post_json = $this->request;
        $result = $this->sendInfo('ecservice/checkOrderStatus', $post_json);
        $this->successReturn($result);
        //print_r($result);
    }

    public function checkOrderStatusAjax($data)
    {
        $post_json['tradeNoList'] = $data;
        $result = $this->sendInfo('ecservice/checkOrderStatus', $post_json);
        return $result;
        //print_r($result);
    }

    // 6.5.4 订单退货通知
    public function backGoodsApplyReturn($data)
    {
        $post_json ['isApplyPass'] = 'yes';
        $post_json ['failReason'] = '无';
        $post_json ['tradeNo'] = $data ['out_apply_id'];
        $post_json ['backNo'] = $data ['order_no'] . '_back';
        $jsons = json_decode($data ['api_param']);
        $post_json ['backAddress'] = $jsons ['getAddress'];
        $result = $this->sendInfo('info/backGoodsApplyReturn', $post_json);
        print_r($result);
    }

    // 6.7.1 分包信息
    public function sendLogisticPackageInfo()
    {
        // 模拟数据
        $data ['out_order_no'] = "20220802131104935002";
        $data ['order_no'] = "CS20220802131104935002";
        $data ['express_no'] = "1227441834762";
        $data ['express'] = "邮政快递";
        $data ['expect_time'] = "2022-08-08";
        $data ['cart_info'] = array();
        $temp ['goods_sku'] = '4177c90b-c7fb-4f84-be5c-48dd4aed60bf';
        $temp ['goods_num'] = 2;
        array_push($data ['cart_info'], $temp);
        $temp ['goods_sku'] = '4177c90b-c7fb-4f84-be5c-48dd4aed60bf';
        $temp ['goods_num'] = 2;
        array_push($data ['cart_info'], $temp);
        // 数据模拟结束
        $post_json ['tradeNO'] = $data ['out_order_no'];
        $post_json ['isAllSend'] = true;
        $post_json ['packages'] = array();
        $i = 0;
        foreach ($data ['cart_info'] as $key => $val) {
            $temp ['packageNo'] = '23026';
            $temp ['sku'] = $val ['goods_sku'];
            $temp ['num'] = $val ['goods_num'];
            $temp ['logisticsNo'] = $data ['express_no'];
            $temp ['logisticsType'] = $data ['express'];
            array_push($post_json ['packages'], $temp);
        }
        $result = $this->sendInfo('ecservice/sendLogisticPackageInfo', $post_json);
        print_r($result);
    }

    public function ajaxLogisticPackageInfo($post_json)
    {
        $result = $this->sendInfo('ecservice/sendLogisticPackageInfo', $post_json);
        // 保存分包日志
        $junResultdb = new JunResultdb();
        $save_result = [];
        $save_result['order_no'] = $post_json ['tradeNO'];
        $save_result['result'] = json_encode($result);
        $save_result['api'] = '发货';
        $save_result['create_time'] = date('Y-m-d H:i:s');
        $junResultdb->save($save_result);
        if (!$result['isSuccess'] && $result['returnMsg'] != '订单未确认') {
            //失败 回滚数据
            $orderdb = new Orderdb();
            $get_order = $orderdb->where('out_order_no', $save_result['order_no'])->find();
            $get_order->save(['shopping_state' => 1, 'shopping_time' => null, 'order_state' => 2]);
            $expressdb = new Expressdb();
            $get_express = $expressdb->where('order_no', $get_order['order_no'])->select();
            foreach ($get_express as $key => $val) {
                $val->save(['order_no' => '']);
            }
            $cartdb = new Cartdb();
            $get_chats = $cartdb->where('order_no', $get_order['order_no'])->select();
            foreach ($get_chats as $key => $val) {
                $val->save(['pack_state' => 2, 'pack_id' => null]);
            }
        }
        return $result;
    }

    // 6.7.3 包裹投妥
    public function sendPackageOverNotice($tradeNo, $packageNo)
    {
        // 模拟数据
        $post_json['tradeNo'] = $tradeNo;
        $post_json['packageNo'] = $packageNo;
        $result = $this->sendInfo('ecservice/sendPackageOverNotice', $post_json);
        print_r($result);
    }

    //6.7.3 包裹投妥 循环
    public function sendPackageOverNoticeWhile()
    {
        // 模拟数据
        $package_arr = [31370, 30509, 30462, 30955];
        $post_json['tradeNo'] = '20221108115227057001';
        for ($i = 0; $i < count($package_arr); $i++) {
            $post_json['packageNo'] = $package_arr[$i];
            $result = $this->sendInfo('ecservice/sendPackageOverNotice', $post_json);
            print_r($result);
        }

    }

    public function ajaxPackageOverNotice($post_json)
    {
        $result = $this->sendInfo('ecservice/sendPackageOverNotice', $post_json);
        // 保存物流日志
        $junResultdb = new JunResultdb();
        $save_result = [];
        $save_result['order_no'] = $post_json ['tradeNo'];
        $save_result['result'] = json_encode($result);
        $save_result['api'] = '已妥投';
        $save_result['create_time'] = date('Y-m-d H:i:s');
        $junResultdb->save($save_result);
        if (!$result['isSuccess'] && $result['returnMsg'] != '订单不处于待妥投状态') {
            //if (!$result['isSuccess']) {
            //失败 回滚数据
            $orderdb = new Orderdb();
            $get_order = $orderdb->where('out_order_no', $save_result['order_no'])->find();
            $get_order->save(['receipt_state' => 1, 'receipt_time' => null, 'order_state' => 3]);

            $expressdb = new Expressdb();
            $get_express = $expressdb->where('order_no', $get_order['order_no'])->select();
            foreach ($get_express as $key => $val) {
                $val->save(['receipt_state' => 1, 'receipt_time' => null]);
            }
            $cartdb = new Cartdb();
            $get_chats = $cartdb->where('order_no', $get_order['order_no'])->select();
            foreach ($get_chats as $key => $val) {
                $val->save(['receipt_state' => 2, 'receipt_time' => null]);
            }
        }
        return $result;
    }

    // 6.8.1 确认收款接口 tradeNo 自采平台订单号
    public function ajaxConfirmReceipt($post_json)
    {
        $result = $this->sendInfo('ecservice/confirmReceipt', $post_json);
        return $result;
    }

    // 6.6.2 推送发票信息
    public function sendInvoiceInfo($out_order_no)
    {
        $orderdb = new Orderdb ();
        $order_no = $out_order_no;
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        if (count($get_order) == 0) {
            $this->errorReturn('没有获取到信息');
        }
        $order_no = $get_order ['order_no'];
        $post_json ['order_no'] = $order_no;
        $data = $this->sendInfoUTEC('getInvoiceInfo', $post_json);
        $return ['invoiceInfo'] = array();
        $temp ['invoiceType'] = $data ['data'] ['invoice_type'] == 1 ? 2 : 1;
        $temp ['invoiceNo'] = $data ['data'] ['fapiaohao'] ?? $get_order['order_id'];
        $temp ['invoiceMoney'] = $data ['data'] ['invoice_money'];
        $orderdb->update(['invoice_state' => 2, 'invoice_time' => time()], ['order_id' => $get_order['order_id']]);
        if ($data ['data'] ['state'] == 2) {
            $temp ['invoiceUrl'] = $data ['data'] ['invoice_proof'] ['save_path'];
        }

        array_push($return ['invoiceInfo'], $temp);
        $return ['tradeNo'] = $get_order['out_order_no'];
        $result = $this->sendInfo('ecservice/sendInvoiceInfo', $return);
        // 保存物流日志
        $junResultdb = new JunResultdb();
        $save_result = [];
        $save_result['order_no'] = $out_order_no;
        $save_result['result'] = json_encode($result);
        $save_result['api'] = '推送发票';
        $save_result['create_time'] = date('Y-m-d H:i:s');
        $junResultdb->save($save_result);

        $UOrderdb = new UOrderdb();
        $get_uorder = $UOrderdb->where('out_order_no', $out_order_no)->find();
        if ($get_uorder) {
            $get_uorder->save(['invoice_state' => 2, 'invoice_time' => time()]);
            $UInvoicedb = new UInvoicedb();
            $get_uinvoice = $UInvoicedb->where('order_nos', $get_uorder['order_no'])->find();
            if ($get_uinvoice) {
                $get_uinvoice->save(['invoice_proof' => $data ['data'] ['invoice_proof']['upload_id']]);
            }
        }

        return $result;
    }

    // 6.7.4 快递100 推送物流
    public function sendLogisticsKuaidi($order_id, $post_data, $kdresult_id)
    {
        $orderdb = new Orderdb();
        $get_order = $orderdb->find($order_id);
        if ($get_order) {
            $return ['logisticsInfo'] = array();
            $postwuliudb = new Postwuliudb();
            $get_wuliu = $postwuliudb->where('order_id', $order_id)->count();
            if ($get_wuliu > 1) {
                $kdresultdb = new Kdresultdb();
                // 获取最后推送时间
                $get_last_time = $kdresultdb->where('order_id', $order_id)->where('kdresult_id', '<>', $kdresult_id)
                    ->order('kdresult_id', 'desc')->find();
                for ($i = 0; $i < count($post_data); $i++) {
                    $temp['operateInfo'] = $post_data[$i]['context'];
                    $temp['operateTime'] = $post_data[$i]['time'];
                    $temp['position'] = $post_data[$i]['areaName'] ?: '北京';
                    if ($post_data[$i]['status'] == '揽收') {
                        $temp['sendState'] = 1;
                    } elseif ($post_data[$i]['status'] == '签收') {
                        $temp['sendState'] = 3;
                    } else {
                        $temp['sendState'] = 2;
                    }
                    if ($get_last_time) {
                        if ($post_data[$i]['time'] > $get_last_time['last_date']) {
                            array_push($return ['logisticsInfo'], $temp);
                        }
                    } else {
                        array_push($return ['logisticsInfo'], $temp);
                    }

                }
                /*$temp['operateInfo'] = $post_data[0]['context'];
                $temp['operateTime'] = $post_data[0]['time'];
                $temp['position'] = $post_data[0]['areaName'] ?: '北京';
                if ($post_data[0]['status'] == '揽收') {
                    $temp['sendState'] = 1;
                } elseif ($post_data[0]['status'] == '签收') {
                    $temp['sendState'] = 3;
                } else {
                    $temp['sendState'] = 2;
                }
                array_push($return ['logisticsInfo'], $temp);*/
            } else {
                foreach ($post_data as $key => $val) {
                    $temp['operateInfo'] = $val['context'];
                    $temp['operateTime'] = $val['time'];
                    $temp['position'] = $val['areaName'] ?: '北京';
                    if ($val['status'] == '揽收') {
                        $temp['sendState'] = 1;
                    } elseif ($val['status'] == '签收') {
                        $temp['sendState'] = 3;
                    } else {
                        $temp['sendState'] = 2;
                    }
                    array_push($return ['logisticsInfo'], $temp);
                }
            }
            $return ['tradeNo'] = $get_order['out_order_no'];
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $get_order ['order_no'];
            $get_list = $expressdb->where('order_no', $get_order['order_no'])->select();
            //halt($get_list->toArray());
            foreach ($get_list as $key => $val) {
                $return ['packageNo'] = $val ['express_id'];
                $result = $this->sendInfo('ecservice/sendOrderLogistics', $return);
                // 保存物流日志
                $junResultdb = new JunResultdb();
                $save_result = [];
                $save_result['order_no'] = $get_order['out_order_no'];
                $save_result['result'] = json_encode($result);
                $save_result['api'] = '推送物流';
                $save_result['create_time'] = date('Y-m-d H:i:s');
                $junResultdb->save($save_result);
                return $result;
                //return $result;
                //print_r($result);
            }
            /*$result = $this->sendInfo('ecservice/sendOrderLogistics', $return);
            return $result;*/
        }
    }

    // 6.7.4 推送物流信息
    public function sendOrderLogistics($out_order_no)
    {
        $orderdb = new Orderdb ();
        $order_no = $out_order_no;
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        //$return ['sendState'] = $get_order ['shopping_state'] == 1 ? 1 : 2;
        $memberdb = new Memberdb();
        $set_member_id = $get_order['supplier_er'] ? $get_order['supplier_er'] : $get_order['supplier_id'];
        $get_member = $memberdb->where('member_id', $set_member_id)->find();
        $get_name = $get_member['order_member'] ?? '';
       // $get_phone = $get_member['order_phone'] ?? '';
        $get_phone =  '400-0888-037';
        $get_d_member = $get_member['delivery_member'] = $get_member['delivery_member'] ?? '';
       // $get_d_phone = $get_member['delivery_phone'] = $get_member['delivery_phone'] ?? '';
         $get_d_phone =  '400-0888-037';
        $return ['logisticsInfo'] = array();
        $base_time = strtotime($get_order['gys_fh_time']);
        $position = $get_order['gys_province'] . '-' . $get_order['gys_city'];
        if (!in_array($get_order['wuliu'], ['圆通速递', '韵达快递', '申通快递', '中通快递', '顺丰速运', 'EMS', '京东物流', '邮政标准快递', '德邦快递', '德邦', '百世快递', '中通快运', '韵达快运', '京东快运', '百世快运', '丰网速运', '宅急送', '顺丰快运', '安能快运', '速必达', '天天快递', '极兔速递', '日日顺物流', '袋鼠速递', '大动脉物流', '丹鸟'])) {
            if ($get_order ['gys_fh_state'] == 1 && $get_order ['gys_sh_state'] == 2) {
                $temp['operateInfo'] = "您已下单成功";
                $temp['operateTime'] = $get_order['create_time'];
                $temp['position'] = $position;
                $temp['sendState'] = 1;
                array_push($return ['logisticsInfo'], $temp);
                $handel_date = date('Y-m-d H:i', strtotime($get_order['create_time']) + rand(60, 5 * 60));
                $get_phone = '400-0888-037';
                $temp['operateInfo'] = "您的订单预计" . $handel_date . "开始处理，请您耐心等待，如您对订单有问题，可联系" . $get_name . "，手机号" . $get_phone;
                $temp['operateTime'] = date('Y-m-d H:i:s', strtotime($get_order['create_time']) + rand(1, 59));
                $temp['position'] = $position;
                $temp['sendState'] = 1;
                array_push($return ['logisticsInfo'], $temp);
            }
            if ($get_order ['shopping_state'] > 1 && $get_order ['gys_sh_state'] == 2) {
                $temp['operateInfo'] = "您的订单由北京市泰龙吉贸易有限公司为您发货，预计" . $get_order['post_date'] . "派送";
                $temp['operateTime'] = date('Y-m-d H:i:s', $base_time);
                $temp['position'] = $position;
                $temp['sendState'] = 2;
                array_push($return ['logisticsInfo'], $temp);


                $temp['operateInfo'] = "您的订单发货凭证已打印完成";
                $temp['operateTime'] = date('Y-m-d H:i:s', ($base_time + rand(1, 59)));
                $temp['position'] = $position;
                $temp['sendState'] = 2;
                array_push($return ['logisticsInfo'], $temp);
                //拣货定时任务
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单已拣货完成";
                $peisong_time = ($base_time + rand(60 * 60, 120 * 60));
                // 如果大于晚上6点 修改到第二天
                if (date('H', $peisong_time) >= 18) {
                    $peisong_time += 46800;
                }

                $temps ['operateTime'] = date('Y-m-d H:i:s', $peisong_time);
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $peisong_time;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
                // 打包完成定时任务
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单已打包完成";
                $peisong_time = ($peisong_time + rand(30 * 60, 60 * 60));
                // 如果大于晚上6点 修改到第二天
                if (date('H', $peisong_time) >= 18) {
                    $peisong_time += 50400;
                }
                $temps ['operateTime'] = date('Y-m-d H:i:s', $peisong_time);
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $peisong_time;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);

                // 分拣完成定时任务
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单已在" . $position . "仓库分拣完成";
                $temps ['operateTime'] = date('Y-m-d H:i:s', ($peisong_time + rand(1, 59)));
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = strtotime($temps ['operateTime']);
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
                // 订单出库
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单正在出库，请耐心等待";
                $temps ['operateTime'] = date('Y-m-d H:i:s', ($peisong_time + rand(60, 120)));
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $peisong_time;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
                // 派送预计到达信息
                $runs = [];
                $temps = [];
                $get_d_phone = '400-0888-037';
                $h = 8;
                if ($get_order['post_date'] == date('Y-m-d')) {
                    // 如果是今天  则时间不能超过现在 否则随机8点到18点
                    $h = rand(date('H') + 3, 17);
                } else {
                    $h = rand(8, 17);
                }
                $d_date = $get_order['post_date'] . ' ' . $h . ':00';
                $get_d_date = date('Y-m-d H:i:s', strtotime($d_date) + rand(61, 59 * 60));
                $temps ['operateInfo'] = "您的订单由北京市泰龙吉贸易有限公司自行派送，快递已离开【" . $position . "】发往您所在城市,预计" . $get_order['delivery_date'] . "送达。如有问题联系" . $get_d_member . "，" . $get_d_phone . "。";
                $temps ['operateTime'] = $get_d_date;
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = strtotime($get_d_date);
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);

                // 派送员
                $runs = [];
                $temps = [];
                $get_d_phone = '400-0888-037';
                $temps ['operateInfo'] = "北京市泰龙吉贸易有限公司正在为您派送，派件员：" . $get_d_member . "，供应商电话：" . $get_d_phone . "。";
                $hs = rand(8, 18);
                $ht = rand(1, 59);
                $d_dates = $get_order['delivery_date'] . ' ' . $hs . ':' . $ht;
                $d_times = strtotime($d_dates);
                if($d_times <= strtotime($get_d_date)){
                    // 如果配送员时间小于出库时间 随机+10-60分钟
                    $d_times = strtotime($get_d_date) + rand(10*60,60*60);
                }
                $temps ['operateTime'] = date('Y-m-d H:i:s', $d_times);
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $d_times;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
            }
            if ($get_order ['receipt_state'] == 2 && $get_order ['gys_sh_state'] == 1) {
                //$return ['sendState'] = 3;

                // 逻辑 如果定时器还有数据没推送 这保存的定时器定时推送 如果没有 则立即推送
                $runsdb = new Runsdb();
                $chk_runs = $runsdb->where('order_no', $get_order['order_no'])
                    ->where('state', 2)
                    ->order('times desc')
                    ->find();
                if ($chk_runs) {
                    $runs = [];
                    $temps = [];
                    $get_d_phone = '400-0888-037';
                    $temps ['operateInfo'] = '您的快递已由【' . $get_order['qianshouyuan'] . '】签收，如有疑问请联系派件员：' . $get_d_member . '【' . $get_d_phone . '】 ，您的快递已经妥投，期待再次为您服务！北京市泰龙吉贸易有限公司官方客服电话：400-0888-037';
                    $d_dates = $chk_runs['times'] + rand(3600, 7200);
                    $temps ['operateTime'] = date('Y-m-d H:i:s',$d_dates);
                    $temps ['position'] = $position;
                    $temps ['sendState'] = 3;
                    array_push($runs, $temps);
                    $save_runs['order_no'] = $get_order['order_no'];
                    $save_runs['out_order_no'] = $get_order['out_order_no'];
                    $save_runs['info'] = json_encode($runs);
                    $save_runs['times'] = $d_dates;
                    $runsdb = new Runsdb();
                    $runsdb->save($save_runs);
                } else {
                    $get_d_phone = '400-0888-037';
                    $temp ['operateInfo'] = '您的快递已由【' . $get_order['qianshouyuan'] . '】签收，如有疑问请联系派件员：' . $get_d_member . '【' . $get_d_phone . '】 ，您的快递已经妥投，期待再次为您服务！北京市泰龙吉贸易有限公司官方客服电话：400-0888-037';
                    $temp ['position'] = $position;
                    $temp ['operateTime'] = $get_order ['receipt_time'];
                    $temp['sendState'] = 3;
                    $return['logisticsInfo'] = [];
                    array_push($return ['logisticsInfo'], $temp);
                }
            }
            //$return ['logisticsInfo'] = end($return ['logisticsInfo']);
            $return ['tradeNo'] = $get_order['out_order_no'];
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $get_order ['order_no'];
            $get_list = $expressdb->ajaxList();
            $back = [];
            foreach ($get_list as $key => $val) {
                $return ['packageNo'] = $val ['express_id'];
                ///halt($return);
                $result = $this->sendInfo('ecservice/sendOrderLogistics', $return);
                // 保存物流日志
                $junResultdb = new JunResultdb();
                $save_result = [];
                $save_result['order_no'] = $out_order_no;
                $save_result['result'] = json_encode($result);
                $save_result['api'] = '推送物流';
                $save_result['create_time'] = date('Y-m-d H:i:s');
                $junResultdb->save($save_result);
                return $result;
                //print_r($result);
            }
            return $back;
        }
    }
    public function sendOrderLogisticstest($out_order_no)
    {
        $orderdb = new Orderdb ();
        $order_no = $out_order_no;
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        //$return ['sendState'] = $get_order ['shopping_state'] == 1 ? 1 : 2;
        $memberdb = new Memberdb();
        $set_member_id = $get_order['supplier_er'] ? $get_order['supplier_er'] : $get_order['supplier_id'];
        $get_member = $memberdb->where('member_id', $set_member_id)->find();
        $get_name = $get_member['order_member'] ?? '';
        $get_phone = $get_member['order_phone'] ?? '';
        $get_d_member = $get_member['delivery_member'] = $get_member['delivery_member'] ?? '';
        $get_d_phone = $get_member['delivery_phone'] = $get_member['delivery_phone'] ?? '';
        $return ['logisticsInfo'] = array();
        $base_time = strtotime($get_order['gys_fh_time']);
        $position = $get_order['gys_province'] . '-' . $get_order['gys_city'];
        if (!in_array($get_order['wuliu'], ['圆通速递', '韵达快递', '申通快递', '中通快递', '顺丰速运', 'EMS', '京东物流', '邮政标准快递', '德邦快递', '德邦', '百世快递', '中通快运', '韵达快运', '京东快运', '百世快运', '丰网速运', '宅急送', '顺丰快运', '安能快运', '速必达', '天天快递', '极兔速递', '日日顺物流', '袋鼠速递', '大动脉物流', '丹鸟'])) {
            if ($get_order ['gys_fh_state'] == 1 && $get_order ['gys_sh_state'] == 2) {
                $temp['operateInfo'] = "您已下单成功";
                $temp['operateTime'] = $get_order['create_time'];
                $temp['position'] = $position;
                $temp['sendState'] = 1;
                array_push($return ['logisticsInfo'], $temp);
                $handel_date = date('Y-m-d H:i', strtotime($get_order['create_time']) + rand(60, 5 * 60));
                $temp['operateInfo'] = "您的订单预计" . $handel_date . "开始处理，请您耐心等待，如您对订单有问题，可联系" . $get_name . "，手机号" . $get_phone;
                $temp['operateTime'] = date('Y-m-d H:i:s', strtotime($get_order['create_time']) + rand(1, 59));
                $temp['position'] = $position;
                $temp['sendState'] = 1;
                array_push($return ['logisticsInfo'], $temp);
            }
            if ($get_order ['shopping_state'] > 1 && $get_order ['gys_sh_state'] == 2) {
                $temp['operateInfo'] = "您的订单由北京市泰龙吉贸易有限公司为您发货，预计" . $get_order['post_date'] . "派送";
                $temp['operateTime'] = date('Y-m-d H:i:s', $base_time);
                $temp['position'] = $position;
                $temp['sendState'] = 2;
                array_push($return ['logisticsInfo'], $temp);


                $temp['operateInfo'] = "您的订单发货凭证已打印完成";
                $temp['operateTime'] = date('Y-m-d H:i:s', ($base_time + rand(1, 59)));
                $temp['position'] = $position;
                $temp['sendState'] = 2;
                array_push($return ['logisticsInfo'], $temp);
                //拣货定时任务
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单已拣货完成";
                $peisong_time = ($base_time + rand(60 * 60, 120 * 60));
                // 如果大于晚上6点 修改到第二天
                if (date('H', $peisong_time) >= 18) {
                    $peisong_time += 46800;
                }

                $temps ['operateTime'] = date('Y-m-d H:i:s', $peisong_time);
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $peisong_time;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
                // 打包完成定时任务
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单已打包完成";
                $peisong_time = ($peisong_time + rand(30 * 60, 60 * 60));
                // 如果大于晚上6点 修改到第二天
                if (date('H', $peisong_time) >= 18) {
                    $peisong_time += 50400;
                }
                $temps ['operateTime'] = date('Y-m-d H:i:s', $peisong_time);
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $peisong_time;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);

                // 分拣完成定时任务
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单已在" . $position . "仓库分拣完成";
                $temps ['operateTime'] = date('Y-m-d H:i:s', ($peisong_time + rand(1, 59)));
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = strtotime($temps ['operateTime']);
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
                // 订单出库
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单正在出库，请耐心等待";
                $temps ['operateTime'] = date('Y-m-d H:i:s', ($peisong_time + rand(60, 120)));
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $peisong_time;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
                // 派送预计到达信息
                $runs = [];
                $temps = [];
                $h = 8;
                if ($get_order['post_date'] == date('Y-m-d')) {
                    // 如果是今天  则时间不能超过现在 否则随机8点到18点
                    $h = rand(date('H') + 3, 17);
                } else {
                    $h = rand(8, 17);
                }
                $d_date = $get_order['post_date'] . ' ' . $h . ':00';
                $get_d_date = date('Y-m-d H:i:s', strtotime($d_date) + rand(61, 59 * 60));
                $temps ['operateInfo'] = "您的订单由北京市泰龙吉贸易有限公司自行派送，快递已离开【" . $position . "】发往您所在城市,预计" . $get_order['delivery_date'] . "送达。如有问题联系" . $get_d_member . "，" . $get_d_phone . "。";
                $temps ['operateTime'] = $get_d_date;
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = strtotime($get_d_date);
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);

                // 派送员
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "北京市泰龙吉贸易有限公司正在为您派送，派件员：" . $get_d_member . "，供应商电话：" . $get_d_phone . "。";
                $hs = rand(8, 18);
                $ht = rand(1, 59);
                $d_dates = $get_order['delivery_date'] . ' ' . $hs . ':' . $ht;
                $d_times = strtotime($d_dates);
                if($d_times <= strtotime($get_d_date)){
                    // 如果配送员时间小于出库时间 随机+10-60分钟
                    $d_times = strtotime($get_d_date) + rand(10*60,60*60);
                }
                $temps ['operateTime'] = date('Y-m-d H:i:s', $d_times);
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $d_times;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
            }
            if ($get_order ['receipt_state'] == 2 && $get_order ['gys_sh_state'] == 1) {
                //$return ['sendState'] = 3;

                // 逻辑 如果定时器还有数据没推送 这保存的定时器定时推送 如果没有 则立即推送
                $runsdb = new Runsdb();
                $chk_runs = $runsdb->where('order_no', $get_order['order_no'])
                    ->where('state', 2)
                    ->order('times desc')
                    ->find();
                if ($chk_runs) {
                    $runs = [];
                    $temps = [];
                    $temps ['operateInfo'] = '您的快递已由【' . $get_order['qianshouyuan'] . '】签收，如有疑问请联系派件员：' . $get_d_member . '【' . $get_d_phone . '】 ，您的快递已经妥投，期待再次为您服务！北京市泰龙吉贸易有限公司官方客服电话：010-21728181';
                    $d_dates = $chk_runs['times'] + rand(3600, 7200);
                    $temps ['operateTime'] = date('Y-m-d H:i:s',$d_dates);
                    $temps ['position'] = $position;
                    $temps ['sendState'] = 3;
                    array_push($runs, $temps);
                    $save_runs['order_no'] = $get_order['order_no'];
                    $save_runs['out_order_no'] = $get_order['out_order_no'];
                    $save_runs['info'] = json_encode($runs);
                    $save_runs['times'] = $d_dates;
                    $runsdb = new Runsdb();
                    $runsdb->save($save_runs);
                } else {
                    $temp ['operateInfo'] = '您的快递已由【' . $get_order['qianshouyuan'] . '】签收，如有疑问请联系派件员：' . $get_d_member . '【' . $get_d_phone . '】 ，您的快递已经妥投，期待再次为您服务！北京市泰龙吉贸易有限公司官方客服电话：010-21728181';
                    $temp ['position'] = $position;
                    $temp ['operateTime'] = $get_order ['receipt_time'];
                    $temp['sendState'] = 3;
                    $return['logisticsInfo'] = [];
                    array_push($return ['logisticsInfo'], $temp);
                }
            }
            //$return ['logisticsInfo'] = end($return ['logisticsInfo']);
            $return ['tradeNo'] = $get_order['out_order_no'];
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $get_order ['order_no'];
            $get_list = $expressdb->ajaxList();
            $back = [];
            foreach ($get_list as $key => $val) {
                $return ['packageNo'] = $val ['express_id'];
                //halt($return);
                $result = $this->sendInfo('ecservice/sendOrderLogistics', $return);
                // 保存物流日志
                $junResultdb = new JunResultdb();
                $save_result = [];
                $save_result['order_no'] = $out_order_no;
                $save_result['result'] = json_encode($result);
                $save_result['api'] = '推送物流';
                $save_result['create_time'] = date('Y-m-d H:i:s');
                $junResultdb->save($save_result);
                return $result;
                //print_r($result);
            }
            return $back;
        }
    }

    // 推送发货信息 备份
    public function sendOrderLogistics_back($out_order_no)
    {
        $orderdb = new Orderdb ();
        $order_no = $out_order_no;
        $orderdb->param ['out_order_no'] = $order_no;
        $get_order = $orderdb->ajaxOrderNo();
        //$return ['sendState'] = $get_order ['shopping_state'] == 1 ? 1 : 2;
        $memberdb = new Memberdb();
        $set_member_id = $get_order['supplier_er'] ? $get_order['supplier_er'] : $get_order['supplier_id'];
        $get_member = $memberdb->where('member_id', $set_member_id)->find();
        $get_name = $get_member['order_member'] ?? '';
        $get_phone = $get_member['order_phone'] ?? '';
        $get_d_member = $get_member['delivery_member'] = $get_member['delivery_member'] ?? '';
        $get_d_phone = $get_member['delivery_phone'] = $get_member['delivery_phone'] ?? '';
        $return ['logisticsInfo'] = array();
        $base_time = strtotime($get_order['gys_fh_time']);
        $position = $get_order['gys_province'] . '-' . $get_order['gys_city'];
        if (!in_array($get_order['wuliu'], ['圆通速递', '韵达快递', '申通快递', '中通快递', '顺丰速运', 'EMS', '京东物流', '邮政标准快递', '德邦快递', '德邦', '百世快递', '中通快运', '韵达快运', '京东快运', '百世快运', '丰网速运', '宅急送', '顺丰快运', '安能快运', '速必达', '天天快递', '极兔速递', '日日顺物流', '袋鼠速递', '大动脉物流', '丹鸟'])) {
            if ($get_order ['gys_fh_state'] == 1 && $get_order ['gys_sh_state'] == 2) {
                $temp['operateInfo'] = "您的订单已生成【" . $get_name . "，" . $get_phone . "】";
                $temp['operateTime'] = $get_order['create_time'];
                $temp['position'] = $position;
                $temp['sendState'] = 1;
                array_push($return ['logisticsInfo'], $temp);
            }
            if ($get_order ['shopping_state'] > 1 && $get_order ['gys_sh_state'] == 2) {
                $temp ['operateInfo'] = '您的订单正在备货，请耐心等待';
                $temp ['operateTime'] = date('Y-m-d H:i', ($base_time - rand(61 * 60, 90 * 60)));
                $temp ['position'] = $position;
                $temp ['sendState'] = 2;
                array_push($return ['logisticsInfo'], $temp);

                $temp ['operateInfo'] = '您的订单正在分拣';
                $temp ['operateTime'] = date('Y-m-d H:i', ($base_time - rand(30 * 60, 60 * 60)));
                $temp ['position'] = $position;
                $temp ['sendState'] = 2;
                array_push($return ['logisticsInfo'], $temp);

                $temp ['operateInfo'] = '您的订单已出库';
                $temp ['operateTime'] = $get_order ['gys_fh_time'];
                $temp ['position'] = $position;
                $temp ['sendState'] = 2;
                array_push($return ['logisticsInfo'], $temp);
                //运输保存定时任务
                $runs = [];
                $temps = [];
                $temps ['operateInfo'] = "您的订单正在运输中【" . $get_d_member . "，" . $get_d_phone . "】";
                $peisong_time = ($base_time + rand(30 * 60, 60 * 60));
                $temps ['operateTime'] = date('Y-m-d H:i', $peisong_time);
                $temps ['position'] = $position;
                $temps ['sendState'] = 2;
                array_push($runs, $temps);
                $save_runs['order_no'] = $get_order['order_no'];
                $save_runs['out_order_no'] = $get_order['out_order_no'];
                $save_runs['info'] = json_encode($runs);
                $save_runs['times'] = $peisong_time;
                $runsdb = new Runsdb();
                $runsdb->save($save_runs);
            }
            if ($get_order ['receipt_state'] == 2 && $get_order ['gys_sh_state'] == 1) {
                //$return ['sendState'] = 3;
                $temp ['operateInfo'] = '已妥投';
                $temp ['position'] = $position;
                $temp ['operateTime'] = $get_order ['receipt_time'];
                $temp['sendState'] = 3;
                $return['logisticsInfo'] = [];
                array_push($return ['logisticsInfo'], $temp);
            }
            //$return ['logisticsInfo'] = end($return ['logisticsInfo']);
            $return ['tradeNo'] = $get_order['out_order_no'];
            $expressdb = new Expressdb ();
            $expressdb->param ['order_no'] = $get_order ['order_no'];
            $get_list = $expressdb->ajaxList();
            $i = 0;
            $back = [];
            foreach ($get_list as $key => $val) {
                $return ['packageNo'] = $val ['express_id'];
                ///halt($return);
                $result = $this->sendInfo('ecservice/sendOrderLogistics', $return);
                // 保存物流日志
                $junResultdb = new JunResultdb();
                $save_result = [];
                $save_result['order_no'] = $out_order_no;
                $save_result['result'] = json_encode($result);
                $save_result['api'] = '推送物流';
                $save_result['create_time'] = date('Y-m-d H:i:s');
                $junResultdb->save($save_result);
                return $result;
                //print_r($result);
            }
            return $back;
        }
    }

    // 6.5.6 申请订单废止
    public function applyStopOrder()
    {
        $get_data = $this->request;
        $out_order_no = $get_data['tradeNo'];
        $reason = $get_data['reason'];
        $files = $get_data['files'];
        $post_type = $get_data['post_type'] ?? 0;
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
        $return['reason'] = $reason;
        $return['files'] = $files;
        $return['is_feizhi'] = $post_type == 0 ? 4 : 3;
        $get_order->save($return);
        // 写日志
        $log_data['order_no'] = $get_order['order_no'];
        $log_data['member_id'] = MEMBER_ID;
        $log_data['view_text'] = '申请订单废止';
        $log_data['post_json'] = $get_data;
        $log_data['type_index'] = 0;
        $orderLogdb = new OrderLogdb();
        $orderLogdb->save($log_data);

        $return['tradeNo'] = $get_order['out_order_no'];
        $return['reason'] = $get_data['reason'];
        $return['files'] = $get_data['files'];

        if ($post_type == 0) {
            // 军采提交的
            $this->successReturn([]);
        } else {
            //  优仕提交的
            $result = $this->sendInfo('ecservice/applyStopOrder', $return);
            return $result;
        }
    }

    // 6.5.7 验证审核订单状态
    public function isStopOrder()
    {
        $get_data = $this->request;
        $out_order_no = $get_data['tradeNo'];
        $isStop = $get_data['isStop'];
        $opinion = $get_data['opinion'];
        $post_type = $get_data['post_type'] ?? 0;
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('out_order_no', $out_order_no)->find();
        $return['opinion'] = $opinion;
        $return['is_feizhi'] = $isStop == 1 ? 1 : 2;
        if ($isStop == 1) {
            $return['order_state'] = -1;
            $return['cancel_time'] = time();
            $return['cancel_type'] = 1; // 用户取消的
        }
        $get_order->save($return);
        // 写日志
        $log_data['order_no'] = $get_order['order_no'];
        $log_data['member_id'] = MEMBER_ID;
        $log_data['view_text'] = '审核废止订单';
        $log_data['post_json'] = $get_data;
        $log_data['type_index'] = 0;
        $orderLogdb = new OrderLogdb();
        $orderLogdb->save($log_data);
        $return['tradeNo'] = $get_order['out_order_no'];
        $return['isStop'] = $return['is_feizhi'];
        if ($post_type == 0) {
            // 军采提交的
            $this->successReturn([]);
        } else {
            //  优仕提交的
            $result = $this->sendInfo('ecservice/isStopOrder', $return);
            return $result;
        }
    }

    // 6.9.2 审核订单售后接口
    public function isAfterSale($returned_id)
    {
        $returneddb = new Returneddb();
        $get_returned = $returneddb->where('returned_id', $returned_id)->order('create_time', 'desc')->find();
        if ($get_returned) {
            if ($get_returned['returned_state'] == 2) {
                // 退货完成
                $save_data = [];
                $save_data['tradeNo'] = str_replace('CS', '', $get_returned['order_no']);
                $save_data['afterSaleID'] = $get_returned['out_apply_id'];
                $result = $this->sendInfo('ecservice/completeAfterSale', $save_data);
                return $result;
            } else {
                $save_data = [];
                $save_data['tradeNo'] = str_replace('CS', '', $get_returned['order_no']);
                $save_data['afterSaleID'] = $get_returned['out_apply_id'];
                $save_data['isAfterSale'] = $get_returned['returned_state'] == 4 ? 1 : 0;
                $save_data['opinion'] = $get_returned['returned_remark'];
                $result = $this->sendInfo('ecservice/isAfterSale', $save_data);
                return $result;
            }

        }
    }

    // 6.9.3 完成订单售后接口
    public function completeAfterSale($returned_id)
    {
        $returneddb = new Returneddb();
        $get_returned = $returneddb->where('returned_id', $returned_id)->order('create_time', 'desc')->find();
        if ($get_returned) {
            $save_data = [];
            $save_data['tradeNo'] = str_replace('CS', '', $get_returned['order_no']);
            $save_data['afterSaleID'] = $get_returned['out_apply_id'];
            $result = $this->sendInfo('ecservice/completeAfterSale', $save_data);
            return $result;
        }
    }

    public function sendInfoUTEC($string_uri, $post)
    {
        $post ['config'] = $this->ys_config;
        $json_data = json_encode($post);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->ys_config ['geteway'] . $string_uri);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-type: application/json;charset='utf-8'"
        ));
        $result = curl_exec($ch);
        curl_close($ch);
        return json_decode($result, true);
    }

    // 成功返回值
    public function successReturn($data)
    {
        $return = $data;
        if (!isset ($return ['resultMsg'])) {
            $return ['resultMsg'] = 'success';
        }
        $return ['isSuccess'] = true;
        $this->ajaxReturn($return);
    }

    // 失败返回值
    public function errorReturn($msg)
    {
        $return ['isSuccess'] = false;
        $return ['resultMsg'] = $msg;
        $this->ajaxReturn($return);
    }

}
